{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个简单的模型\n",
    "class SimpleModel(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(SimpleModel, self).__init__()\n",
    "        self.fc = nn.Linear(10, 2)\n",
    "    def forward(self, x):\n",
    "        return self.fc(x)\n",
    "\n",
    "\n",
    "model = SimpleModel()\n",
    "optimizer = optim.SGD(model.parameters(), lr = 0.01)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from copy import deepcopy\n",
    "model2 = deepcopy(model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成两组不同的数据\n",
    "x1 = torch.randn(3, 10)\n",
    "y1 = torch.randint(0, 2, (3,))\n",
    "x2 = torch.randn(4, 10)\n",
    "y2 = torch.randint(0, 2, (4,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算第一个loss\n",
    "output1 = model(x1)\n",
    "loss1 = nn.CrossEntropyLoss()(output1, y1)\n",
    "# 计算第二个loss\n",
    "output2 = model(x2)\n",
    "loss2 = nn.CrossEntropyLoss()(output2, y2)\n",
    "\n",
    "# 累积两个loss并进行backward\n",
    "(loss1 + loss2).backward()\n",
    "# 更新参数\n",
    "optimizer.step()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[ 2.0225e-01, -2.6471e-01, -6.3388e-02,  1.9838e-01, -4.7733e-02,\n",
      "          3.0902e-01,  2.8144e-02,  2.3918e-01, -5.6085e-02, -2.0738e-01],\n",
      "        [-2.3701e-01, -1.5774e-01, -4.3788e-02,  2.6193e-02, -2.9406e-01,\n",
      "          5.3136e-02,  2.0396e-02, -2.1860e-02,  1.0565e-04,  1.5462e-01]],\n",
      "       requires_grad=True)\n"
     ]
    }
   ],
   "source": [
    "print(model.fc.weight)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "disc",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
